package com.laomou.password.ui;

import com.laomou.password.R;
import com.laomou.password.db.SQLitePersistentObject;


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;


public class NewAddActivity extends Activity implements AdapterView.OnItemSelectedListener {
    private Spinner mSpinner;
    private EditText mAccount;
    private EditText mPassword;
    private Password mData;
    private SharedPreferences mPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newadd);
        mSpinner = (Spinner) findViewById(R.id.spinner);
        mSpinner.setAdapter(ArrayAdapter.createFromResource(this, R.array.account_type, android.R.layout.simple_spinner_item));
        mSpinner.setOnItemSelectedListener(this);
        mAccount = (EditText) findViewById(R.id.account);
        mPassword = (EditText) findViewById(R.id.password);
        mData = new Password();
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_newadd, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (item.getItemId() == R.id.menu_save) {
            mData.account = mAccount.getText().toString();
            mData.password = mPassword.getText().toString();
            if (mData.isEmpty()) {
                setResult(-1);
            } else {
                new SQLitePersistentObject(this, mData).save();
                setResult(9);
            }
            finish();
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mData.pkg = getResources().getStringArray(R.array.account_type_value)[position];
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        mData.pkg = null;
    }
}
